package com.cicigodd.brick.plug.common.config.knife4j;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;


/**
 * @author cicigodd
 * @date 2022-09-26 16:59
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    /**
     * 定义分隔符
     */
    private static final String splitor = ";";

    @Value("${knife4j.swagger.title}")
    private String title;
    @Value("${knife4j.swagger.description}")
    private String description;
    @Value("${knife4j.swagger.version}")
    private String version;
    @Value("${knife4j.swagger.packages}")
    private String packages;
    @Value("${knife4j.swagger.contact}")
    private String contact;

    @Bean(value = "dockerBean")
    public Docket dockerBean() {
        //指定使用Swagger2规范
        Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(
                        new ApiInfoBuilder()
                                .title(title)
                                .description(description)
                                .version(version)
                                .contact(new Contact(contact, null, null))
                                .build()
                )
                //分组名称
                .select()
                //这里指定Controller扫描包路径
                .apis(basePackage(packages + splitor + "com.cicigodd.brick"))
                .paths(PathSelectors.any()).build();
        return docket;
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
